<?php

namespace app\helper;

use phpseclib3\Crypt\RSA as CryptRSA;

class Rsa
{

    /**
     * rsa加密
     *
     * @param string $content 加密内容
     * @param string $public_key 公钥
     * @return string
     */
    public static function rsa_encode(string $content, string $public_key): string
    {

        $publicKey = CryptRSA::loadPublicKey($public_key)->withPadding(CryptRSA::ENCRYPTION_PKCS1);
        return base64_encode($publicKey->encrypt($content));

    }


    /**
     * rsa解密
     *
     * @param string $encodeStr 解密内容
     * @param string $private_key 私钥
     */
    public static function rsa_decode(string $encodeStr, string $private_key)
    {

        $privateKey = CryptRSA::loadPrivateKey($private_key)->withPadding(CryptRSA::ENCRYPTION_PKCS1);
        $content = base64_decode($encodeStr);

        return $privateKey->decrypt($content);

    }


    /**
     * 创建公钥 私钥
     *
     * @return array
     */
    public static function rsa_create(): array
    {

        $private = CryptRSA::createKey();
        $public = $private->getPublicKey();

        return [
            'private_key' => $private,
            'public_key' => $public
        ];

    }

}